package com.framework.base.taglib.ui; 

import java.io.IOException;
import java.lang.reflect.Field;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.BodyTagSupport;

import org.apache.log4j.Logger;

import com.framework.base.util.BeanUtil;
import com.framework.base.util.StringUtil;
import com.framework.main.sys.attachment.domain.AttachmentVo;

/**
 * Description:用于输出附件列表，并提供下载得操作
 * tabaleName(对应的表名):
 * Company: framework
 * @author：HYH
 * @version 1.0
 * @Date Jun 11, 2011 12:14:22 AM
 */  
@SuppressWarnings("serial")
public class FileDownLoad extends BodyTagSupport {
	private String foreignId;//外键引用
	private String showProperties="";//需要显示的属性 注意以逗号以尾 默认显示文件名
	private static  Logger logger = Logger.getLogger(FileDownLoad.class); // 作为日志的公用对象
	private String fileType="";  //文件上传类型用|隔开（为空：可以上传任意类型）默认不受限制
	private String fileCount=""; //限制文件数（为0：不受限制）,默认只能上传一个附件
	private String userTypef;    //模块业务类型，默认业务类型为0，如果一个表单中有多个地方上传附件，业务类型从0依次递增
	private String  showType;    //显示类型，list table:显示列表类型，view fileName:只显示附件名称
	private String disabled;     //按钮是否变灰(true or false)
	
	public String getFileType() {
		return fileType;
	}
	public void setFileType(String fileType) {
		this.fileType = fileType;
	}
	public String getFileCount() {
		return fileCount;
	}
	public void setFileCount(String fileCount) {
		this.fileCount = fileCount;
	}
	 
	public String getUserTypef() {
		return userTypef;
	}
	public void setUserTypef(String userTypef) {
		this.userTypef = userTypef;
	}
	public String getShowType() {
		return showType;
	}
	public void setShowType(String showType) {
		this.showType = showType;
	}
	@Override
	public int doStartTag() throws JspException {
		HttpServletRequest httpRequest = (HttpServletRequest) pageContext.getRequest();
		//多/单上传类型，并且控制上传数量
		if(StringUtil.nullToEmpty(fileCount).length()>0){
			int counts=Integer.parseInt(fileCount);
			if(counts>1){
			}else if(counts<=0){
				fileCount="0";
			}else{
				fileCount="1";
			}
		}else{
			fileCount="0";
		}
		//附件类型
		if(StringUtil.nullToEmpty(fileType).length()>0){
			/*if(fileType.indexOf("|")<=0){
				logger.error("定义的文件类型没有用|隔开");
				return EVAL_BODY_INCLUDE;
			}*/
			fileType="accept='"+fileType+"'";
		}
		//业务类型
		if(StringUtil.nullToEmpty(userTypef).length()==0){
			userTypef="0";
		}
		//显示类型
		if(StringUtil.nullToEmpty(showProperties).length()==0){
			showType="view";
		}else{
			showType="list";
		}
		
		if(StringUtil.nullToEmpty(disabled).length()>0&&disabled.equals("true")){
			disabled="disabled='true'";
		}else{
			disabled="";
		}
		//获取相应的附件列有
		List<AttachmentVo> voList=BeanUtil.getAttachmentService().toAttachmentListByforeignId(getForeignId(),userTypef);
		StringBuffer uploadFile=new StringBuffer();
		uploadFile.append("<input type='hidden' name='button_"+userTypef+"' id='button_"+userTypef+"' value="+voList.size()+"><table width=\"100%\" align='center' bordercolorlight='#95A4B2' bordercolordark='#FFFFFF' border='0' cellspacing='0' >");
		if(disabled.length()<=0){
			uploadFile.append("<tr class=\"td4\">");
			uploadFile.append("<td align=\"left\" class=\"subsys_td2\"><input type=\"file\" "+disabled+" id=\"attachment_"+userTypef+"\"  name=\"attachment\" class=\"multi\" userTypef='"+userTypef+"' showType='"+showType+"' maxlength=\""+fileCount+"\" "+fileType+"></td>");
			uploadFile.append("</tr>");
		}
		boolean isViewTr=false;
		//构建显示内容
		StringBuffer content=new StringBuffer("<table width=\"100%\" align='center' bordercolorlight='#95A4B2' bordercolordark='#FFFFFF' border='0' cellspacing='0' >");
		for (AttachmentVo attachmentVo : voList) {
			//构建下载的url
			String downloadUrl=httpRequest.getContextPath()+"/attatoDownLoad.action?downloadType="+attachmentVo.getFileTypef()+"&downloadName="+attachmentVo.getFileNamef()
			+"&diskFileName="+attachmentVo.getDiskFilePathf();
			content.append("<tr>");
			content.append("<td  width=\"20%\">");
			content.append("<a href=\"").append(downloadUrl).append("\" onclick=\"return isReaderFile('"+attachmentVo.getIdf()+"')\" >").append(attachmentVo.getFileNamef()).append("</a>");
			content.append("</td>");
			isViewTr=true;
			if(StringUtil.nullToEmpty(showProperties).length()>0){
				String[] propertyNames=showProperties.split(",");
				for (String propertyName : propertyNames) {
					try {
						Field field=attachmentVo.getClass().getDeclaredField(propertyName);
						field.setAccessible(true);
						String fieldValue=StringUtil.getStringFromObj(field.get(attachmentVo));
						content.append("<td width=\"20%\">");
						content.append(fieldValue);
						content.append("</td>");
					} catch (Exception e) {
						e.printStackTrace();
						logger.error(e.toString());
					} 
				}
			}
			content.append("<td>");
			if(disabled.length()<=0){
				content.append("<a href=\"#\" onclick=\"ev_deleteFile('"+attachmentVo.getIdf()+"','"+userTypef+"');\">删除</a>");
			}/*else{
				content.append("删除");
			}*/
			content.append("</td>");
			content.append("</tr>");
		}
		content.append("</table>");
		if(isViewTr){
			uploadFile.append("<tr id=\"delTr\" class=\"td4\">");
			uploadFile.append("<td class=\"subsys_td3\" colspan=\"2\" >"+content+"</td>");
			uploadFile.append("</tr>");
		}
		uploadFile.append("</table>");
		uploadFile.append("<script type=\"text/javascript\">");
		uploadFile.append(" var fileMaxLengh=$('#attachment_"+userTypef+"').attr('maxlength');");
		uploadFile.append(" var hiddenLengh=$('#button_"+userTypef+"').val();");
		uploadFile.append(" if(parseFloat(hiddenLengh)==parseFloat(fileMaxLengh)&&parseFloat(fileMaxLengh)>0){");
		uploadFile.append("    $('#attachment_"+userTypef+"').attr('disabled',true); ");
		uploadFile.append(" }");
		uploadFile.append("</script>");
		JspWriter out = pageContext.getOut();
		try {
			out.write(uploadFile.toString());
		} catch (IOException e) {
			e.printStackTrace();
			logger.error(e.toString());
		}
		
		return EVAL_BODY_INCLUDE;
	}
	@Override
	public int doEndTag() throws JspException {
		JspWriter out = pageContext.getOut();
		
		try {
			out.print("</a>");
		} catch (IOException e) {
			e.printStackTrace();
		}
		return super.doEndTag();
	}
	public String getForeignId() {
		return foreignId;
	}
	public void setForeignId(String foreignId) {
		this.foreignId = foreignId;
	}
	public String getShowProperties() {
		return showProperties;
	}
	public void setShowProperties(String showProperties) {
		this.showProperties = showProperties;
	}
	public String getDisabled() {
		return disabled;
	}
	public void setDisabled(String disabled) {
		this.disabled = disabled;
	}
}
